<?php
/**
 * Created by PhpStorm.
 * User: ylq
 * Date: 2018/8/14
 * Time: 11:50
 */

namespace app\api\core\wechat;


use app\api\core\CreateUuid;

use Yii;
use Cm;
class wxReply extends wechat
{
    /**
     * 授权微信公总号的appid
     * @var
     */
    public $wx_appid;

    /**
     * 数据库id
     * @var
     */
    public $wx_account_id;

    /**
     * 用户openid
     * @var
     */
    public $openid;

    /**
     * 公总号微信号
     * @var
     */
    private $wx_number;
    /**
     * wxReply constructor.
     * @param $wx_appid
     * @param string $openid
     */
    public function __construct($wxappid, $openid, $accountnumber='')
    {
        parent::__construct();

        $this->wx_appid = $wxappid;

        $this->openid = $openid;

        $wxInfo = Cm::$db->one("select id, accountnumber,accountverifytype,accountappsecret from scrm_weixin_account WHERE accountappid='{$this->wx_appid}'");

        $this->wx_number = isset($wxInfo['accountnumber'])  ? $wxInfo['accountnumber'] : $accountnumber;

        $this->wx_account_id = isset($wxInfo['id'])  ? $wxInfo['id'] : $this->wx_app_data_id;

    }

    /**
     * 验证数据存在不
     * @return bool
     */
    public function checkAuth()
    {
        if ($this->getAuthInfo($this->wx_appid)) {
            return !empty($this->wx_number) ? true : false;
        }
        return false;
    }

    /**
     * 关注
     */
    public function subscribe()
    {
        (new wxUser())->getUserInfo($this->wx_appid, $this->openid, true);

        echo 'success';exit;
        echo 'success';

        $data = $this->subscribeReply();
        if (!$data) {
            echo 'success';
        }
        echo $data;
    }

    /**
     * 取消关注
     */
    public function unsubscribe()
    {
        $sql = "select id,subscribe from `scrm_weixin_customer` WHERE openid='{$this->openid}'";
        $data = Cm::$db->one($sql);

        if ($data) {
            $is_new_add = 0;
            $time = strtotime(date('Y-m-d ', strtotime($data['subscribe'])));
            $now = strtotime(date('Y-m-d'));
            if ($now==$time) {
                $is_new_add = 1;
            }
            Cm::$db->update('scrm_weixin_customer', [
               'status'=>2,
                'is_new_add'=>$is_new_add,
                'unsubscribe'=>date('Y-m-d H:i:s')
            ], "openid='{$this->openid}'");
        }

        echo 'success';
    }

    /**

     * 接受文本信息
     */
    public function receiveText($result, $wxid='')
    {
        $id=(new CreateUuid())->toString();
        $data = [
           'id'=>$id,
            'wx_account_id'=>$wxid,
            'to_user_name'=>$result['ToUserName'],
            'from_user_name'=>$this->openid,
            'create_time'=>date('Y-m-d H:i:s', $result['CreateTime']),
            'add_time'=>date('Y-m-d H:i:s'),
            'msg_type'=>1,
            'content'=>$result['Content'],
            'msg_id'=>$result['MsgId'],
        ];
        Cm::$db->insert('scrm_weixin_message', $data);

        return $this->keyText($data['content'], $id);
    }
    /**
     * 接受文本信息并回复
     */
    public function keyText($keys, $id=0)
    {
        $sql = "SELECT id,preg,keywords  
        FROM `scrm_weixin_keywords` 
        WHERE wx_account_id='{$this->wx_account_id}' and 
        CASE
            when preg = 0 then keywords='{$keys}'
            when preg = 1 then keywords LIKE '%{$keys}%'
        END";
        $keywords = Cm::$db->one($sql);


        YII_DEBUG && self::logResult("/{key_words}.log","发送用户的消息【json源数据】".$sql);
        YII_DEBUG && self::logResult("/{key_words}.log","发送用户的消息【json源数据】".json_encode($keywords, JSON_UNESCAPED_UNICODE));

        $result = [];

        if ($keywords)  {
            $config = Cm::$db->one("SELECT id,key_id,key_item_id,type,content,media_id
            FROM `scrm_weixin_keywords_config` 
            WHERE key_item_id='{$keywords['id']}'");
            if ($config) {
                switch ($config['type']) {
                    case 'text':
                        $result = [
                            'type'=>1,
                            'content'=>$config['content'],
                            'msg_id'=>$id,
                            'key_item_id'=>$config['key_item_id'],
                            'keys'=>$keys,
                        ];
                        break;
                    case 'image':
                        $result = [
                            'type'=>2,
                            'media_id'=>$config['media_id'],
                        ];
                        break;
                    case 'video':
                            $data = Cm::$db->one("SELECT m.title, m.media_id,m.intro 
                            FROM `scrm_weixin_fover_material` as m
                            inner join scrm_weixin_account as a on a.id=m.wx_account_id
                            WHERE a.accountappid='{$this->wx_appid}' 
                            and m.type='video' 
                            and m.media_id='{$config['media_id']}'");
                            if ($data) {
                                $result = [
                                    'type'=>4,
                                    'media_id'=>$config['media_id'],
                                    'title'=>$data['title'],
                                    'description'=>$data['intro'],
                                ];
                            }
                        break;
                    case 'voice':
                        $result = [
                            'type'=>3,
                            'media_id'=>$config['media_id'],
                        ];
                        break;
                    case 'news':
                        $news = Cm::$db->one("SELECT m.id FROM `scrm_weixin_fover_material` as m
                        inner join scrm_weixin_account as a on a.id=m.wx_account_id
                        WHERE a.accountappid='{$this->wx_appid}' 
                        and m.type='news'  
                        and m.media_id='{$config['media_id']}'");

                        if ($news) {
                            $items = Cm::$db->all("SELECT title, digest,content_source_url,thumb_url,url from scrm_weixin_fover_material_items 
                WHERE material_id='{$news['id']}'");
                            if ($items) {
                                $item = [];
                                foreach ($items as $row) {
                                    $item [] = [
                                        'Title'=>$row['title'],
                                        'Description'=>$row['digest'],
                                        'PicUrl'=>$row['thumb_url'],
                                        'Url'=>!empty($row['content_source_url']) ? $row['content_source_url'] : $row['url'],
                                    ];
                                }
                                if (count($item) < 1) {
                                    echo 'success';
                                }
                                $result=[
                                    'type'=>6,
                                    'create_time'=>date('Y-m-d H:i:s'),
                                    'article_count'=>count($item),
                                    'articles'=>$item
                                ];
                            }
                        }
                        //组合数据：
                        break;
                    case 'template':
                        break;
                }
            }
        }
        if (empty($result)) {
            $result['type'] = 10;
        }
        return $this->replyMsg($result);
    }

    /**
     * 回复用户消息
     * @return bool|string
     */
    public function replyMsg($result, $sentType='send_msg')
    {
        if (!$this->checkAuth()) {
            return false;
        }
        $data = [
            'ToUserName'=>$this->openid,
            'FromUserName'=>$this->wx_number,
            'CreateTime'=>time(),
        ];

        /**
         *       'msg_id'=>$id,
        'key_itme_id'=>$config['key_item_id'],
        'keys'=>$keys,
         */
        $replayLog = array_filter([
            'id'=>(new CreateUuid())->toString(),
            'wx_account_id'=>$this->wx_account_id,
            'to_user_name'=>$this->openid,
            'from_user_name'=>$this->wx_number,
            'add_time'=>date('Y-m-d H:i:s'),
            'key_id'=>isset($result['key_item_id']) ? $result['key_item_id'] : 0,
            'type'=>isset($result['type']) ? $result['type'] : 0,
            'key'=>isset($result['keys']) ? $result['keys'] : '',
            'message_id'=>isset($result['msg_id']) ? $result['msg_id'] : '',
            'content'=>isset($result['content']) ? $result['content'] : (isset($result['media_id']) ? $result['media_id'] : 0),
        ]);
        if (isset($replayLog['key']) && !empty($replayLog['key'])) {
            Cm::$db->insert('scrm_weixin_keywords_msg_log', $replayLog);
        }
        if (!$result) {

            $data['MsgType'] = 'text';
            $data['Content'] = '欢迎您！谢谢你的关注，我们竭尽全力为你服务。';
        }

        //1:文本， 2：图片，3：语音，4：视屏 5：多图文 6：音乐
        switch ((int)$result['type']) {
            case 1:#回复文本消息
                $data['MsgType']='text';
                $data['Content']=$result['content'];
                break;
            case 2:#回复图片消息

                $data['MsgType']='image';
                $data['MediaId']=$result['media_id'];
                break;
            case 3:#回复语音消息
                $data['MsgType']='voice';
                $data['MediaId']=$result['media_id'];

                break;
            case 4:#回复视频消息
                $data['MsgType']='video';
                $data['MediaId']=$result['media_id'];
                if (isset($result['title']) && !empty($result['title'])) {
                    $data['Title']=$result['title'];
                }
                if (isset($result['description']) && !empty($result['description'])) {
                    $data['Description']=$result['description'];
                }
                break;
            case 5:#回复音乐消息
                $data['MsgType']='music';
                $data['ThumbMediaId']=$result['thumb_media_id'];
                if (isset($result['title']) && !empty($result['title'])) {
                    $data['Title']=$result['title'];
                }
                if (isset($result['description']) && !empty($result['description'])) {
                    $data['Description']=$result['description'];
                }
                if (isset($result['music_url']) && !empty($result['music_url'])) {
                    $data['MusicURL']=$result['music_url'];
                }
                if (isset($result['hq_music_url']) && !empty($result['hq_music_url'])) {
                    $data['HQMusicUrl']=$result['hq_music_url'];
                }
                break;
            case 6:#回复图文消息
                $data['MsgType']='news';
                $data['ArticleCount']=$result['article_count'];
                $data['Articles']=$result['articles'];
                $data['Title']=$result['title'];
                break;
            default:
                $data['MsgType'] = 'text';
                $data['Content'] = '欢迎您！谢谢你的关注，我们竭尽全力为你服务。';
                break;
        }

        //写入数据：

        YII_DEBUG && self::logResult("/beidong_reply_msg.log","被动回复用户的数据【json源数据】、回复格式：{$data['MsgType']}：".json_encode($data, JSON_UNESCAPED_UNICODE));
        $nonce      = empty($_GET['nonce'])     ? ""    : trim($_GET['nonce']) ;
        $msg = self::cryptArrayToXml($data, $nonce);
        echo $msg;

    }

    /**
     * 接受图片
     */

    public function receiveImage($result, $wxid='')
    {
        $data = [
            'id'=>(new CreateUuid())->toString(),
            'wx_account_id'=>$wxid,
            'to_user_name'=>$result['ToUserName'],
            'from_user_name'=>$this->openid,
            'create_time'=>date('Y-m-d H:i:s', $result['CreateTime']),
            'pic_url'=>$result['PicUrl'],
            'add_time'=>date('Y-m-d H:i:s'),
            'msg_type'=>2,
            'msg_id'=>$result['MsgId'],
            'media_id'=>$result['MediaId'],
        ];
        Cm::$db->insert('scrm_weixin_message', $data);
        echo 'success';
    }

    /**
     * 接受语音
     */
    public function receiveVoice($result, $wxid='')
    {
        $data = [
            'id'=>(new CreateUuid())->toString(),
            'wx_account_id'=>$wxid,
            'to_user_name'=>$result['ToUserName'],
            'from_user_name'=>$this->openid,
            'create_time'=>date('Y-m-d H:i:s', $result['CreateTime']),
            'add_time'=>date('Y-m-d H:i:s'),
            'msg_type'=>3,
            'msg_id'=>$result['MsgId'],
            'media_id'=>$result['MediaId'],
            'format'=>$result['Format'],
            'recognition'=>json_encode($result['Recognition']),
        ];
        Cm::$db->insert('scrm_weixin_message', $data);
        echo 'success';
    }

    /**
     * 接受视频
     */
    public function receiveVideo($result, $wxid='')
    {
        $data = [
            'id'=>(new CreateUuid())->toString(),
            'wx_account_id'=>$wxid,
            'to_user_name'=>$result['ToUserName'],
            'from_user_name'=>$this->openid,
            'create_time'=>date('Y-m-d H:i:s', $result['CreateTime']),
            'add_time'=>date('Y-m-d H:i:s'),
            'msg_type'=>4,
            'msg_id'=>$result['MsgId'],
            'media_id'=>$result['MediaId'],
            'thumb_media_id'=>$result['ThumbMediaId'],

        ];
        Cm::$db->insert('scrm_weixin_message', $data);
        echo 'success';
    }

    /**
     * 关注回复内容
     * @return bool|string
     */
    public function subscribeReply()
    {
        if (!$this->checkAuth()) {
            return false;
        }
        $data = [];
        $result = Cm::$db->one("
            SELECT a.accountappid,a.accountappsecret,a.accountnumber,r.* 
            FROM `scrm_weixin_subscribe_reply`  r
            INNER JOIN `scrm_weixin_account` a ON r.wx_account_id=a.id 
            WHERE a.accountappid='{$this->wx_appid}'"
        );

        $data = [
            'ToUserName'=>$this->openid,
            'FromUserName'=>$this->wx_number,
            'CreateTime'=>time(),
        ];

        if (!$result) {

            $data['MsgType'] = 'text';
            $data['Content'] = '欢迎您！谢谢你的关注，我们竭尽全力为你服务。';
        }

        //1:文本， 2：图片，3：语音，4：视屏 5：多图文 6：音乐
        switch ((int)$result['type']) {
            case 1:#回复文本消息
                $data['MsgType']='text';
                $data['Content']=$result['content'];
                break;
            case 2:#回复图片消息

                $data['MsgType']='image';
                $data['MediaId']=$result['media_id'];
                break;
            case 3:#回复语音消息
                $data['MsgType']='voice';
                $data['MediaId']=$result['media_id'];

                break;
            case 4:#回复视频消息
                $data['MsgType']='video';
                $data['MediaId']=$result['media_id'];
                if (isset($result['title']) && !empty($result['title'])) {
                    $data['Title']=$result['title'];
                }
                if (isset($result['description']) && !empty($result['description'])) {
                    $data['Description']=$result['description'];
                }
                break;
            case 5:#回复音乐消息
                $data['MsgType']='music';
                $data['ThumbMediaId']=$result['thumb_media_id'];
                if (isset($result['title']) && !empty($result['title'])) {
                    $data['Title']=$result['title'];
                }
                if (isset($result['description']) && !empty($result['description'])) {
                    $data['Description']=$result['description'];
                }
                if (isset($result['music_url']) && !empty($result['music_url'])) {
                    $data['MusicURL']=$result['music_url'];
                }
                if (isset($result['hq_music_url']) && !empty($result['hq_music_url'])) {
                    $data['HQMusicUrl']=$result['hq_music_url'];
                }
                break;
            case 6:#回复图文消息
                $data['MsgType']='news';
                $data['ArticleCount']=$result['article_count'];
                $data['Articles']=$result['articles'];
                $data['Title']=$result['title'];
                $data['PicUrl']=$result['pic_url'];
                $data['Description']=$result['description'];
                $data['Url']=$result['url'];
                break;
            default:
                $data['MsgType'] = 'text';
                $data['Content'] = '欢迎您！谢谢你的关注，我们竭尽全力为你服务。';
                break;
        }

        //写入数据：

        YII_DEBUG && self::logResult("/beidong_reply_msg.log","被动回复用户的数据【json源数据】、回复格式：{$data['MsgType']}：".json_encode($data, JSON_UNESCAPED_UNICODE));
        $nonce      = empty($_GET['nonce'])     ? ""    : trim($_GET['nonce']) ;
        return self::cryptArrayToXml($data, $nonce);

    }


    /**
     * 写入操作【登陆日志】日志
     * @param $openid
     * @param string $type
     * @param string $data
     * @return bool
     */
    public function writeLoginLog($openid, $type='', $data='', $flag=false)
    {
        $time = isset(Yii::$app->params['login_limit_time']) ? Yii::$app->params['login_limit_time'] : 30*60;

        $customer = Cm::$db->one("SELECT id,wx_account_id,`status` FROM `scrm_weixin_customer` where openid='{$openid}'");

        if ($customer) {
            $date = time();
            $log = [
                'id'=>(new CreateUuid())->toString(),
                'openid'=>$openid,
                'wx_customer_id'=>$customer['id'],
                'date'=>date('Y-m-d H:i:s', $date),
                'create_time'=>$date,
                'user_agent'=>$type,
                'ip'=>$this->get_ip(),
                'option_content'=>json_encode($data)
            ];

            $realation = Cm::$db->one("SELECT company_id FROM `scrm_weixin_company_account` WHERE wx_account_id='{$customer['wx_account_id']}'");

            if ($realation) {
                $log['company_id'] = $realation['company_id'];
            }
            if ($flag) {
                Cm::$db->insert('scrm_weixin_customer_log', $log);
            }
            //取消关注不需要日志
//            $sql = "
//                    SELECT id, openid,create_time
//                    FROM `scrm_weixin_customer_log`
//                    where openid='{$openid}' order by create_time desc ";
            $end = date('Y-m-d H:i:s',$date);
            $start= date('Y-m-d H:i:s',$date-$time);
            $sql = "SELECT id, openid,create_time FROM `scrm_weixin_customer_log` WHERE openid='{$openid}' AND  `date` > '{$start}' and `date` < '{$end}'";
            $data = Cm::$db->one($sql);

            YII_DEBUG && $this->logResult('/login.log','SQL:'."{$sql}"."结果{$time}数据:".json_encode($data));
            if (!$data) {
                //if ($result['create_time']-$date > $time ) {
                    Cm::$db->insert('scrm_weixin_customer_log', $log);
                //}
            //} else {
                //Cm::$db->insert('scrm_weixin_customer_log', $log);
           }

        }

        return true;
    }

}